package com.ctsi.crm.sync.service;

import com.ctsi.commons.util.response.Page;
import com.ctsi.crm.sync.domain.CustInfo;
import com.ctsi.crm.sync.domain.RegionInfo;
import com.ctsi.crm.sync.entity.CrmSyncEntity;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SyncService {

    private static final Logger logger = LoggerFactory.getLogger(SyncService.class);

    private static final String CUST_URL = "http://137.0.249.205:9600/serviceAgent/rest/crm/shandong/saop/customer";

    @Autowired
    private MybatisGenericDao dao;

    public Page<CrmSyncEntity> queryList(Map<String,Object> param , int start , int pageSize){
        logger.debug("selectMulitCondition {}",param);
        if(pageSize<0||pageSize>2000){
            pageSize=Page.DEFAULT_PAGE_SIZE;
        }
        if(start!=-1)
            return dao.queryPage(CrmSyncEntity.class.getName()+".findList", param, start, pageSize);
        else{
            throw new RuntimeException("参数不正确 !!");
        }
    }

    private RestTemplate restTemplate;

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    @PostConstruct
    public void init() {
        this.restTemplate = restTemplateBuilder.additionalInterceptors((request, body, execution) -> {
            HttpHeaders headers = request.getHeaders();
            headers.add("X-APP-ID","77c60d3f110f56afa9d672b8642989f6");
            headers.add("X-APP-KEY","c1f742e18644dc8e6ad956d7c54650bd");
            headers.add("Content-Type","application/json");
            return execution.execute(request, body);
        }).build();
    }

    /**
     * 同步crm系统中的客户信息,有可能是多个，所以返回list
     */
    public List<CustInfo> syncCust(String regionId, String certNum){
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("regionId", "8320100");
        paramMap.put("certType", "1");
        paramMap.put("certNumber", "100000379");
        ParameterizedTypeReference<List<CustInfo>> ptr = new ParameterizedTypeReference<List<CustInfo>>() {};
        ResponseEntity<List<CustInfo>> response = restTemplate.exchange(CUST_URL, HttpMethod.GET,null,ptr,paramMap);
        return response.getBody();
    }

    /**
     * CRM 地域信息
     * @return
     */
    public List<RegionInfo> syncRegion(){
        return (List<RegionInfo>) dao.queryForList(CrmSyncEntity.class.getName()+".queryRegionInfo");
    }

}
